package com.hexb.smh.aop;

import com.hexb.smh.entity.Product;
import com.hexb.smh.entity.enums.ILogCreator;
import com.hexb.smh.entity.enums.Operators;
import com.hexb.smh.service.IProductService;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : hexb
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ToggleBatchProductLogCreator implements ILogCreator, InitializingBean {

    @NonNull
    private final OperationLogFactory factory;

    @NonNull
    private final IProductService productService;

    @Override
    public String create(Object[] args) {
        Integer[] ids = (Integer[]) args[0];
        Boolean activated = (Boolean) args[1];
        String a = activated ? "上架" : "下架";
        List<Product> products = productService.listByIds(ids);
        String s = products.stream().map(p -> String.format("%s(%s)",p.getName(),p.getItemNo())).collect(Collectors.joining(","));
        return String.format("%s%d个项目:%s", a, products.size(), s);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        factory.register(Operators.batchToggleProduct, this);
    }
}
